import requests
from typing import Union
from typing import Optional
import settings
import json
import datetime
from logger_config import setup_logger
from snownlp import SnowNLP
import re

# 设置日志记录器
logger = setup_logger()


class DouyinVideoinfo(object):

    def __init__(self, aweme_id: str):
        self.aweme_id = aweme_id
        try:
            # 发起请求并解析 JSON
            response = requests.get(f'{settings.VIDEO_API_ADDRESS}/api/douyin/web/fetch_one_video?aweme_id={aweme_id}')
            response.raise_for_status()  # 确保响应成功，否则抛出HTTPError
            data = response.json()

            # 从嵌套的数据中提取有效信息
            video_data = data.get('data', {})
            self.title = video_data.get('aweme_detail', {}).get('caption')
            self.owner = video_data.get('aweme_detail', {}).get('author').get('nickname')
            self.like = video_data.get('aweme_detail', {}).get('statistics').get('digg_count')
            self.reply = video_data.get('aweme_detail', {}).get('statistics').get('comment_count')

        except requests.exceptions.RequestException as e:
            # 捕获请求相关的错误（包括网络问题、无效的响应等）
            logger.error(f"Error occurred while fetching Douyin video info for {aweme_id}: {e}")
            self.aweme_id = self.title = self.owner = self.like = self.reply = None

        except ValueError as e:
            # 捕获 JSON 解析错误
            logger.error(f"JSON decode error for Douyin video {aweme_id}: {e}")
            self.aweme_id = self.title = self.owner = self.like = self.reply = None

        except Exception as e:
            # 捕获所有其他类型的错误
            logger.error(f"Unexpected error for Douyin video {aweme_id}: {e}")
            self.aweme_id = self.title = self.owner = self.like = self.reply = None

    def get_info(self) -> dict:
        info = {
            'aweme_id': self.aweme_id,
            'title': self.title,
            'owner': self.owner,
            'like': self.like,
            'reply': self.reply
        }
        return info

    def get_comments(self, cursor: int, count: int = 20) -> list:
        comment_list = list()
        try:
            # 发起请求并解析 JSON
            response = requests.get(
                f'{settings.VIDEO_API_ADDRESS}/api/douyin/web/fetch_video_comments?aweme_id={self.aweme_id}&cursor={cursor}&count={count}')
            response.raise_for_status()  # 确保响应成功，否则抛出HTTPError
            data = response.json()

            # 从嵌套的数据中提取有效信息
            comment_data = data.get('data', {}).get('comments', [])
            for comment in comment_data:
                comment_dict = dict()
                comment_dict['comment_text'] = comment.get('text')
                # 将ctime转换为datetime对象
                date_time = datetime.datetime.fromtimestamp(comment.get('create_time'))
                comment_dict['comment_time'] = date_time
                comment_dict['user_id'] = comment.get('user').get('short_id')
                comment_dict['user_nickname'] = comment.get('user').get('nickname')
                # 使用三元表达式判断
                gender_str = "男" if comment.get('user').get('show_gender_strategy') == 0 else "女"
                comment_dict['user_sex'] = gender_str
                comment_dict['sub_comment_count'] = comment.get('reply_comment_total')
                comment_dict['likes'] = comment.get('digg_count')
                comment_dict['address'] = comment.get('ip_label')
                # 创建 SnowNLP 对象
                s = SnowNLP(comment_dict['comment_text'])
                # 获取情感值，范围为 0 到 1，接近 1 表示积极情感，接近 0 表示消极情感
                sentiment = s.sentiments
                if sentiment < 0.1:
                    sentiment = sentiment + 0.5
                # 四舍五入到小数点后三位
                comment_dict['emotional_value'] = round(sentiment, 3)
                comment_dict['video_id'] = self.aweme_id
                comment_list.append(comment_dict)

        except requests.exceptions.RequestException as e:
            # 捕获请求相关的错误（包括网络问题、无效的响应等）
            logger.error(f"Error occurred while fetching Douyin video info for {self.aweme_id} cursor {cursor}: {e}")
            comment_list = None

        except ValueError as e:
            # 捕获 JSON 解析错误
            logger.error(f"JSON decode error for Douyin video {self.aweme_id} cursor {cursor}: {e}")
            comment_list = None

        except Exception as e:
            # 捕获所有其他类型的错误
            logger.error(f"Unexpected error for Douyin video {self.aweme_id} cursor {cursor}: {e}")
            comment_list = None

        return comment_list


if __name__ == '__main__':
    one = DouyinVideoinfo('7414015680212684044')
    print(one.get_info())
    print(one.get_comments(cursor=20))
